<?php
namespace App\Api\Fcjd;

use PhalApi\Api;
use PhalApi\Exception\BadRequestException;

/**
 * ClearNaN
 * 清理数据中的 NaN 值
 * @author dogstar ClearNaN
 */
class ClearNaN extends Api {
    public function getRules() {
        return array(
            'clear' => array(),
        );
    }

    /**
     * 更新手机号数据
     * @desc 接收JSON数据，清理task和task2字段中的NaN值
     * @return array 返回操作结果，包含处理的记录数
     * @exception 400 数据库操作失败时抛出异常
     */
    public function clear() {
        // 设置跨域头
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *,x-token,X-token');

        try {
            // 查询task或task2包含NaN的记录（同时检查两个字段）
            $records = \PhalApi\DI()->notorm->phone_list
                ->where('task LIKE ? OR task2 LIKE ?', ['%NaN%', '%NaN%'])
                ->fetchAll();

            $totalRecords = count($records);
            $processedCount = 0;
            $updatedCount = 0;

            foreach ($records as $record) {
                $updateData = [];

                // 处理task字段
                if (strpos($record['task'], 'NaN') !== false) {
                    $taskValues = explode(',', $record['task']);
                    $filteredTask = array_filter($taskValues, function($v) {
                        return trim($v) !== 'NaN';
                    });
                    $newTask = implode(',', $filteredTask);
                    if ($newTask !== $record['task']) {
                        $updateData['task'] = $newTask;
                    }
                }

                // 处理task2字段（与task逻辑完全一致）
                if (strpos($record['task2'], 'NaN') !== false) {
                    $task2Values = explode(',', $record['task2']);
                    $filteredTask2 = array_filter($task2Values, function($v) {
                        return trim($v) !== 'NaN';
                    });
                    $newTask2 = implode(',', $filteredTask2);
                    if ($newTask2 !== $record['task2']) {
                        $updateData['task2'] = $newTask2;
                    }
                }

                // 仅当有字段需要更新时执行数据库操作
                if (!empty($updateData)) {
                    $result = \PhalApi\DI()->notorm->phone_list
                        ->where('id', $record['id'])
                        ->update($updateData);
                    if ($result) {
                        $updatedCount++;
                    }
                }

                $processedCount++;
            }

            \PhalApi\DI()->response->setMsg('清理NaN值成功');
            \PhalApi\DI()->response->setRet(200);

            return array(
                'total_records' => $totalRecords,
                'processed_count' => $processedCount,
                'updated_count' => $updatedCount,
                'note' => '同时清理了task和task2字段的NaN值'
            );

        } catch (\Exception $e) {
            throw new BadRequestException('数据处理失败：' . $e->getMessage());
        }
    }
}
